package lex.dm.id3;

import javax.swing.JTree;

import org.lex.swing.Swings;

import lex.dm.utils.Utils;

public class ID3Classification {

	public static void main(String[] args) {
		IDataSet ds = ArrayDataSet.getSampleDataSet();
		DataSetUtils.dump(ds, System.out);
		ID3 id3 = new ID3(ds);
		ID3Node root = id3.createTree();
		JTree tree = new JTree(root);
		Swings.expandAll(tree);
		Swings.show(tree);
		// ------------------
		System.out.println(new ID3Classification().classify(root, ds) + "/" + ds.getRowCount());
	}

	/**
	 * Ӧ��ID3Node root�в�����ж�����򣬶���ݼ����з���
	 * 
	 * @param root
	 * @param dataSet
	 * @return ��ȷԤ��������Ŀ
	 */
	public int classify(ID3Node root, IDataSet dataSet) {
		int valid = 0;
		for (int i = 0, n = dataSet.getRowCount(); i < n; i++) {
			if (true == this.match(root, dataSet, i))
				valid++;
		}
		return valid;
	}

	private boolean match( ID3Node node, IDataSet dataSet, int row )
	{
		//leaf
		if( node.isLeaf() )
		{
			return Utils.equals2( node.leafValue ,dataSet.getValue( row, dataSet.getClassAttributeIndex() ) );
		}
		//root
		else if( null == node.parent )
		{
			String attr = node.attributeName;
			Object value = dataSet.getValue( row, dataSet.getAttributeIndex( attr ) );
			for( ID3Node child : node.children )
				if( Utils.equals2( value, child.parentArrtibuteValue ) )
					return match( child, dataSet, row );
			return false;
		}
		//�м�ڵ�
		else
		{
			String parentAttr = node.parent.attributeName;
			Object value = dataSet.getValue( row, dataSet.getAttributeIndex( parentAttr ) );
			if( Utils.equals2( value, node.parentArrtibuteValue ) )
			{
				for( ID3Node child: node.children )
					if( this.match( child, dataSet, row ))
						return true;
				return false;
			}
			else
			{
				return false;
			}
		}
	}
}
